package com.ryan.ohos.imagepreview.services.velocity;

import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.agp.components.AttrHelper;
import ohos.agp.components.VelocityDetector;
import ohos.rpc.*;
import ohos.utils.zson.ZSONObject;

public class VelocityService extends Ability {

    private static final int CODE_ADD_EVENT = 0;
    private static final int CODE_CALCULATE = 1;
    private static final int CODE_GET_VELOCITY = 2;
    private static final int CODE_CLEAR = 3;

    private final ServiceRemote remote = new ServiceRemote();
    private VelocityDetector detector;
    private TouchEventProxy proxy;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        detector = VelocityDetector.obtainInstance();
        proxy = new TouchEventProxy();
    }

    @Override
    protected IRemoteObject onConnect(Intent intent) {
        super.onConnect(intent);
        return remote.asObject();
    }

    @Override
    public void onDisconnect(Intent intent) {}

    class ServiceRemote extends RemoteObject implements IRemoteBroker {
        ServiceRemote() {
            super("VelocityService");
        }

        @Override
        public boolean onRemoteRequest(int code, MessageParcel data, MessageParcel reply, MessageOption option) {
            switch (code) {
                case CODE_ADD_EVENT:
                    String dataStr = data.readString();
                    Data param = new Data();
                    try {
                        param = ZSONObject.stringToClass(dataStr, Data.class);
                    } catch (RuntimeException e) {
                        e.printStackTrace();
                    }

                    fillProxy(param);
                    detector.addEvent(proxy);

                    reply.writeString("{\"code\":0}");
                    break;

                case CODE_GET_VELOCITY:
                    detector.calculateCurrentVelocity(1000, 8000, 8000);
                    int x = (int) (detector.getHorizontalVelocity());
                    int y = (int) (detector.getVerticalVelocity());
                    reply.writeString("{\"code\":0,\"data\":{\"x\":" + x + ", \"y\":" + y + "}}");
                    break;

                case CODE_CLEAR:
                    detector.clear();
                    reply.writeString("{\"code\":0}");
                    break;
            }
            return true;
        }

        @Override
        public IRemoteObject asObject() {
            return this;
        }
    }

    private void fillProxy(Data param) {
        proxy.setAction(param.action);
        proxy.setTime(System.currentTimeMillis());
        proxy.setPoint(param.x, param.y);
    }
}